package com.duqc;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.duqc.sentinel.controller.UserController;
import com.duqc.sentinel.service.impl.UserServiceImpl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableScheduling
@EnableCaching
@EnableAsync
@EnableTransactionManagement
@EnableApolloConfig
@EnableBatchProcessing
@EnableRetry
@MapperScan(basePackages = {"com.duqc.web.dao.**", "com.duqc.zk.mapper", "com.duqc.quartz",
        "com.duqc.tag.dao", "com.duqc.tag.dao.*",})
@EnableFeignClients(basePackages = "com.duqc.web.feign")
public class SummarizeApplication {

    public static void main(String[] args) {
        SpringApplication.run(SummarizeApplication.class, args);
        //初始化限流规则
        initFlowQpsRule();
    }

    private static void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<>();
        rules.add(setFlowRule(UserController.RESOURCE_NAME));
        rules.add(setFlowRule(UserController.RESOURCE_NAME_QUERY_USER_BY_ID));
        rules.add(setFlowRule(UserServiceImpl.RESOURCE_NAME_QUERY_USER_BY_NAME));
        rules.add(setFlowRule(UserServiceImpl.ADD));
        FlowRuleManager.loadRules(rules);
    }

    private static FlowRule setFlowRule(String resourceName) {
        FlowRule flowRule = new FlowRule(resourceName);
        flowRule.setCount(2);
        flowRule.setLimitApp("default");
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        return flowRule;
    }

}
